﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using Application = System.Windows.Application;

namespace Pujcovna
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        static extern int SetForegroundWindow(IntPtr hWnd);

        // nacist grab-usb spolecne s hlavnim programem
        protected override void OnStartup(StartupEventArgs e)
        {
            var procesy = Process.GetProcessesByName("grab-usb");
            if (procesy.Length == 0 && File.Exists("grab-usb.exe"))
            {
                Process.Start("grab-usb.exe");
                Thread.Sleep(100); // je potreba uspat

                IntPtr hWnd = FindWindow(null, "Snímač");
                if (!hWnd.Equals(IntPtr.Zero)) ShowWindowAsync(hWnd, 0); // 0 - minimalizovat
            }

            base.OnStartup(e);
        }

        // zavrit grab-usb spolecne s hlavnim programem
        protected override void OnExit(ExitEventArgs e)
        {
            var procesy = Process.GetProcessesByName("grab-usb");
            foreach (var proces in procesy.Where(proces => proces.HasExited == false))
                proces.Kill();
        }


        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
            
            // kdyz neni pripojena ctecka
            IntPtr nextW = FindWindow(null, "Chyba");
            if (nextW == IntPtr.Zero) return;
            SetForegroundWindow(nextW);
            SendKeys.SendWait("{ENTER}"); // zavre grab-usb.exe
        }

        void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = false;
            ShowUnhandeledException(e);
        }

        void ShowUnhandeledException(DispatcherUnhandledExceptionEventArgs e)
        {
            LoggerLib.Logger.Log(e);
        }
    }
}
